import requests
from datetime import date, datetime
import csv
from bs4 import BeautifulSoup

# url = 'https://www.bilibili.com/ranking'
url = 'https://www.bilibili.com/v/popular/rank/all'

response = requests.get(url)
html_text = response.text
soup = BeautifulSoup(html_text, 'html.parser')


class Video:
    def __init__(self, rank, title, score, visit, up, up_id, url):
        self.rank = rank
        self.title = title
        self.score = score
        self.visit = visit
        self.up = up
        self.up_id = up_id
        self.url = url

    def to_csv(self):
        return [self.rank, self.title, self.score, self.visit, self.up,
                self.up_id, self.url]

    @staticmethod
    def csv_title():
        return ['排名', '标题', '分数', '播放量', 'Up主', 'Up Id', 'URL']


# 提取列表
items = soup.findAll('li', {'class': 'rank-item'})
Videos = []

for item in items:
    title = item.find('a', {'class': 'title'}).text  # 视频标题
    score = item.find('div', {'class': 'pts'}).find('div').text   # 综合得分
    rank = item.find('div', {'class': 'num'}).text      # 排名
    visit = item.find('span', {'class': 'data-box'}).text.strip()  # 播放量
    up = item.find_all('a')[2].text.strip()  # up名字
    space = item.find_all('a')[2].get('href')
    up_id = space[len('//space.bilibili.com/'):]  # up的id
    url = item.find('a', {'class': 'title'}).get('href')

    v = Video(rank, title, score, visit, up, up_id, url)
    Videos.append(v)

now = datetime.now().strftime('%Y%m%d_%H%M%S')
file_name = f'top100_{now}.csv'
with open(file_name, 'w', newline='', encoding='utf-8-sig') as f:
    pen = csv.writer(f)
    pen.writerow(Video.csv_title())
    for v in Videos:
        pen.writerow(v.to_csv())
